const mongoose=require('mongoose');
const User = require('../models/user.model');

exports.create=function(req,res,next){
    const user = new User(req.body);
    user.save().then(data=>{
      res.json(data);
    })
}

exports.update=function(req,res,next){
   var id = req.params.id;
   User.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
     res.json(data);
   })
}

exports.get=function(req,res,next){
  var id = req.params.id;
  User.findById(id).then(data=>{
    res.json(data);
  })
}

exports.remove=function(req,res,next){
  var id = req.params.id;
  User.findByIdAndRemove(id).then(data=>{
    res.json(data);
  })
}

exports.removes=function(req,res,next){
  var ids = req.body.ids.split(',');
  User.remove({_id: {$in: ids}}).then(()=>{
    res.json({"message":"删除多个数据成功",status:200})
  })
}

exports.list=function(req,res,next){
  var page = req.body.page?req.body.page:1;
  var rows = req.body.rows?req.body.rows:10;

  User.paginate({},{page:+page,limit:+rows},function(err,result){
    result.rows = result.docs;
    delete result.docs;
    res.json(result);
  })
}


exports.search=function(req,res,next){
  var name = req.params.name;
  var page = req.body.page?req.body.page:1;
  var rows = req.body.rows?req.body.rows:10;

  User.paginate({name:new RegExp(name,'g')},{page:+page,limit:+rows},function(err,result){
    result.rows = result.docs;
    delete result.docs;
    res.json(result);
  })
}